﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using UCL.Powersource;

namespace PowersourceUIToolkit
{
    public class ViewConductorBase : InitializedLifeCycleBase, IViewConductor
    {

        protected ViewConductorBase()
        {
            TopContentControl = new ContentControl();
            ViewCacheItems = new List<WeakReference<ViewCacheItem>>();
        }

        public ContentControl TopContentControl { get; private set; }

        protected List<WeakReference<ViewCacheItem>> ViewCacheItems { get; private set; }

        public bool ContainsViewModel(IViewModel vm)
        {
            ViewCacheItem writ = null;
            var vciFromCond = ViewCacheItems.FirstOrDefault(a => { if (a.TryGetTarget(out writ)) return writ.ViewModel == vm; else return false; });
            writ=null;
            return vciFromCond != null;
            
        }

        internal bool ContainsViewCacheItem(ViewCacheItem itForFE)
        {
            ViewCacheItem writ = null;
            var vciFromCond = ViewCacheItems.Where(a => { if (a.TryGetTarget(out writ)) return writ == itForFE; else return false; });
            writ = null; // Used in inner query, reference immediatelly nulled
            if (vciFromCond.Count() > 1) throw new InvalidOperationException(string.Format("ConductorCachedItems contains more then 1 viewcache item for {0} {1}", itForFE.View, itForFE.ViewModel));
            else
                if (vciFromCond.Count() == 1)
                {
                    return true;
                }
                else return false;
        }

       
     
        public FrameworkElement ActiveView { get; private set; }

        public void ActivateViewModel(IViewModel rootModel)
        {
            if (IsDisposed) throw new ObjectDisposedException(this.GetType().FullName);
            var vicToActivate = ViewLocator.GetDefaultCacheItemForViewModel(rootModel);
            var UIManager = IoC.Get<IUIManager>();

            if (vicToActivate == null)//if there is no such control for rootModel viewModel, it will be created and cache will be queried again
            {

                UIManager.GetOrCreateControl(rootModel);
            }
            UIManager.EnsureConductorRegistered(this);
            vicToActivate = ViewLocator.GetDefaultCacheItemForViewModel(rootModel); // try to get CachedItem again
            if (vicToActivate == null) // if we do not succeed on secodn call Control cannot be created 
                throw new InvalidOperationException(string.Format("Unable to create control for viewmodel {0}, while activating that viewmodel in ToolWindowPaneConductor", rootModel.GetType()));
            ViewCacheItem tmpvic = null;
            var refVicToActivate = ViewCacheItems.SingleOrDefault(a => { if (a.TryGetTarget(out tmpvic)) return tmpvic == vicToActivate; else return false; });
            tmpvic = null;
            if (refVicToActivate == null)
            {
                ViewCacheItems.Add(new WeakReference<ViewCacheItem>(vicToActivate));
            }
            ActiveView = vicToActivate.View;
            //ToolWindowContent.Content = null;
            TopContentControl.Content = vicToActivate.View;

        }

     
        protected override bool OnInitializing()
        {
            return true;
        }

        protected override void OnDisposing()
        {
            if (ViewCacheItems != null) ViewCacheItems.Clear();
            ViewCacheItems = null;
        }
    }
}
